package com.vote.wx.service.impl;


import com.vote.common.core.domain.ResponseResult;
import com.vote.common.core.domain.entity.SysUser;
import com.vote.common.core.domain.model.LoginUser;
import com.vote.common.core.redis.RedisCache;
import com.vote.framework.web.service.TokenService;
import com.vote.system.service.ISysUserService;
import com.vote.vote.model.RedisConstants;
import com.vote.wx.service.ApiUserService;
import com.vote.vote.util.RandomUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class ApiUserServiceImpl implements ApiUserService {

    private final ISysUserService userMapper;


    //redis的
    private final RedisCache redisService;
    @Autowired
    private TokenService tokenService;

    /**
     * 判断用户是否微信登录成功
     *
     * @param loginCode 用户临时id
     * @return
     */
    @Override
    public ResponseResult wxIsLogin(String loginCode) {
        SysUser user = redisService.getCacheObject(RedisConstants.WX_LOGIN_USER + loginCode);
//        用户未授权
        if (user == null) return ResponseResult.error("用户未被授权");
        log.info("判断用户是否微信登录成功 user===>{}", user);
//        生成token
        LoginUser loginUser = new LoginUser().setUser(user);

        String token = tokenService.createToken(loginUser);
//        存入token
        user.setToken(token);

        return ResponseResult.success(user);
    }

    /**
     * 微信扫码公众号登录
     *
     * @param message
     * @return
     */
    @Override
    public String wechatLogin(WxMpXmlMessage message) {
        String content = message.getContent().toUpperCase();
        System.err.println("公众号登陆content" + content);
        //先判断登录码是否已过期
        boolean loginFlag = redisService.hasKey(RedisConstants.WX_LOGIN_USER_STATUE + content);
        if (!loginFlag) {
            return "验证码已过期";
        }
        SysUser userInfoVO = wechatInit(message.getFromUser());
        //修改redis缓存 以便监听是否已经授权成功
        redisService.setCacheObject(RedisConstants.WX_LOGIN_USER + content, userInfoVO, 60, TimeUnit.SECONDS);
        return "登陆成功,请返回网页!";
    }


    /**
     * 获取微信公众号登录验证码
     *
     * @return
     */
    @Override
    public ResponseResult getWechatLoginCode() {
        // 登陆验证码 dl+两位数
        String code = "DL" + RandomUtils.generationNumberChar(2);

        redisService.setCacheObject(RedisConstants.WX_LOGIN_USER_STATUE + code, false, 60, TimeUnit.SECONDS);
        return ResponseResult.success(code);
    }

    /**
     * @param openId 用户的id
     * @return com.vote.common.core.domain.entity.SysUser
     * @author WanShen 公众号验证成功 初始化用户
     * @date 2024/1/16 15:09
     */
    private SysUser wechatInit(String openId) {

        SysUser userInfoVO = userMapper.selectUserByUserName(openId);
        try {
            if (userInfoVO != null) return userInfoVO;

            if (userInfoVO == null) {

                // 保存用户信息 可能会异常
                userInfoVO.setNickName("WECHAT-bn" + RandomUtils.generationNumberChar(4));
                userMapper.insertUser(userInfoVO);
            }
            return userInfoVO;

        } catch (Exception e) {
//            用户不存在 新用户
            userInfoVO = new SysUser().setNickName("WECHAT-bn" + RandomUtils.generationNumberChar(4))
                    .setUserName(openId);
//                调用注册的方法
            userMapper.registerUser(userInfoVO);

            return userInfoVO;

        }

    }

}
